package cn.vortex.device.web.filter;

import cn.vortex.device.vo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RoleFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object user = request.getSession().getAttribute("USER");//获取Session存储的User对象
//        System.out.println(user.toString());
//        System.out.println("roleFilter.....");
        if (user != null){//判断user 是否存在
            if (user instanceof User){//判断user是否是User的实例化对象，是返回true
                User _user = (User) user;//将user转换为User对象
                if (_user.getRoleId() == 2) {//判断用户的身份ID是否符合要求
                    filterChain.doFilter(request, response);//满足要求继续执行，访问相应资源
//                    response.sendRedirect(request.getContextPath()+"/page/apply/checkList.jsp");
                } else {
                    response.sendRedirect(request.getContextPath()+"/error/403.html");//不满足将请求转发至403错误页面
                }
            }
            else {
                throw new RuntimeException("传入的USER不符合要求！");//如果user对象不是User类的实例化对象抛出异常
            }
        }
        else {
            response.sendRedirect(request.getContextPath()+"/error/403.html");//不满足将请求转发至403错误页面
        }

    }

    @Override
    public void destroy() {

    }
}
